package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

//生产者
public class ProducerQuickStart {
    public static void main(String[] args){
        //kafka的配置信息
        Properties properties = new Properties();
        //连接kafka
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"124.222.219.178:9092");
        //发送失败,失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);

        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        //生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //封装要发送的消息
        ProducerRecord<String, String> record = new ProducerRecord<String, String>("topic-01","hello kafka");

        //发送消息
        //producer.send(record);
        //异步消息发送
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e != null){
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println(recordMetadata.offset());
            }
        });

        //关闭通道,不关闭消息不会发送成功
        producer.close();

    }
}
